package com.itheima.sevice.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.constant.RedisConstant;
import com.itheima.config.FreeMarkerApplicationConfiguration;
import com.itheima.properties.FreeMarkerProperties;
import com.itheima.sevice.SetmealService;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.dao.SetmealCheckGroupDao;
import com.itheima.dao.SetmealDao;
import com.itheima.pojo.Setmeal;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import freemarker.template.Configuration;

import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private SetmealCheckGroupDao setmealCheckGroupDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private  Configuration configuration;

    @Autowired
    private FreeMarkerProperties freeMarkerProperties;

    /**
     * 新增套餐
     * @param checkgroupIds
     * @param setmeal
     * @return
     */
    @Override
    @Transactional
    public Integer add(List<Integer> checkgroupIds, Setmeal setmeal) throws Exception {
        // 往套餐表添加数据
        Integer recordCount = setmealDao.insert(setmeal);

        if(checkgroupIds != null && checkgroupIds.size() > 0){
            // 往套餐-检查组表中添加数据
            for (Integer checkgroupId : checkgroupIds) {
                setmealCheckGroupDao.insert(setmeal.getId(), checkgroupId);
            }
        }

        if (setmeal.getImg() != null){
            // 将存储到数据库的套餐记录的图片名存储到redis中
            String[] str = setmeal.getImg().split("/");
            String imgName = str[str.length-1];
            redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, imgName);
        }

        // 重新生成静态页面
        createHtmlPage(setmeal);

        return recordCount;
    }

    /**
     * 编辑套餐
     * @param checkgroupIds
     * @param setmeal
     * @return
     */
    @Override
    @Transactional
    public Integer edit(List<Integer> checkgroupIds, Setmeal setmeal) throws Exception {
        // 获取修改前图片名
        String imgName = findById(setmeal.getId()).getImg();

        // 将套餐数据更新到套餐表中
        setmealDao.update(setmeal);

        // 删除原有套餐-检查组表中所有关联当前套餐的检查组记录
        Integer recordCount = setmealCheckGroupDao.deleteBySetmealId(setmeal.getId());

        if(checkgroupIds != null && checkgroupIds.size() > 0){
            // 往套餐-检查组表中添加数据
            for (Integer checkgroupId : checkgroupIds) {
                setmealCheckGroupDao.insert(setmeal.getId(), checkgroupId);
            }
        }

        if (imgName != null){
            // 删除修改前图片名
            redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_DB_RESOURCES, imgName);
        }

        if (setmeal.getImg() != null){
            // 保存修改后图片名
            redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        }

        // 重新生成静态页面
        createHtmlPage(setmeal);

        return recordCount;
    }

    /**
     * 根据id查询套餐数据
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {

        return setmealDao.findById(id);
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> setmealPage = setmealDao.findPage(queryPageBean);

        return new PageResult(setmealPage.getTotal(), setmealPage.getResult());
    }

    /**
     * 重新生成静态页面
     * @throws Exception
     */
    void createHtmlPage(Setmeal setmeal) throws Exception {
        Map<String, Object> map = new HashMap<>();

        configuration.setClassForTemplateLoading(FreeMarkerApplicationConfiguration.class, "/templates");

        //获取套餐页模板
        Template setmealListTemplate = configuration.getTemplate(
                  "mobile_setmeal.ftl");

        List<Integer> setmealIds = setmealDao.findAllSetmealIds();
        List<Setmeal> setmealList = new ArrayList<>();
        for (Integer setmealId : setmealIds) {
            Setmeal setmeal1 = setmealDao.findById(setmealId);
            if (setmeal1.getImg() == null){
                setmeal1.setImg("https://healthitcast.oss-cn-beijing.aliyuncs.com/5f06f7af-aa05-4874-a74b-ed5e14b13450.jpg");
            }
            setmealList.add(setmeal1);
        }
        map.put("setmealList", setmealList);

        setmealListTemplate.process(map, new FileWriter(
                freeMarkerProperties.getOutPath() + "setmeal_1.html"
        ));

        Setmeal setmeal2 = setmealDao.findById(setmeal.getId());
        if (setmeal2.getCheckGroups() != null){
            // 获取套餐详情页模板
            Template setmealTemplate = configuration.getTemplate(
                    "mobile_setmeal_detail.ftl");
            if (setmeal2.getImg() == null){
                setmeal2.setImg("https://healthitcast.oss-cn-beijing.aliyuncs.com/5f06f7af-aa05-4874-a74b-ed5e14b13450.jpg");
            }
            map.put("setmeal", setmeal2);
            setmealTemplate.process(map, new FileWriter(
                    freeMarkerProperties.getOutPath() + "setmeal_detail_" + setmeal2.getId() +".html"
            ));
        }
    }
}
